package setting

import (
	"log"
	"time"

	"github.com/go-ini/ini"
)

type App struct {
	PageSize  int
	JwtSecret string

	RuntimeRootPath string
	PrefixUrl       string
	ExportSavePath  string
	ImageSavePath   string
	QrCodeSavePath  string
	FontSavePath    string
	ImageMaxSize    int
	ImageAllowExts  []string

	LogLevel   string
	LogName    string
	MaxSize    int
	MaxAge     int
	MaxBackups int
	IsCompress bool
}

type Server struct {
	RunMode      string
	HttpPort     int
	ReadTimeout  time.Duration
	WriteTimeout time.Duration
}

type Database struct {
	Type        string
	User        string
	Password    string
	Host        string
	Name        string
	TablePrefix string
}

type Redis struct {
	Host        string
	Password    string
	MaxIdle     int
	MaxActive   int
	IdleTimeout time.Duration
}

var (
	AppSetting      = &App{}
	ServerSetting   = &Server{}
	DatabaseSetting = &Database{}
	RedisSetting    = &Redis{}
)

func Setup() {
	Cfg, err := ini.Load("conf/app.ini")
	if err != nil {
		log.Fatalf("Fail to parse 'conf/app.ini': %v", err)
	}
	config := map[string]interface{}{
		"app":      AppSetting,
		"server":   ServerSetting,
		"database": DatabaseSetting,
		"redis":    RedisSetting,
	}
	for k, v := range config {
		err = Cfg.Section(k).MapTo(v)
		if err != nil {
			log.Fatalf("Cfg.MapTo %v err: %v", k, err)
		}
	}
	AppSetting.ImageMaxSize = AppSetting.ImageMaxSize * 1024 * 1024
	ServerSetting.ReadTimeout = ServerSetting.ReadTimeout * time.Second
	ServerSetting.WriteTimeout = ServerSetting.WriteTimeout * time.Second
	RedisSetting.IdleTimeout = RedisSetting.IdleTimeout * time.Second
}
